package com.film.web.controller;

import com.film.common.util.JwtTokenUtil;
import com.film.pojo.User;
import com.film.pojo.dto.LoginDto;
import com.film.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "用户接口") //构建Api文档  swagger
@RequestMapping("/film-api/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("login")
    @ApiOperation("用户登录")  //构建Api文档
    public Map<String,Object> login(@RequestBody LoginDto dto) throws Exception{
        User user = userService.login(dto);
        Map<String,Object> map = new HashMap<>();
        //是否选择记住我
        //JwtTokenUtil 封装JTW生成token和校验方法
        //REMEMBER_EXPIRATION_TIME 一个星期过期
        //EXPIRATION_TIME  一天过期
        //用三目运算判断 打勾是一个星期过期,不打勾是一天过期
        long exp = dto.isRemember() ? JwtTokenUtil.REMEMBER_EXPIRATION_TIME : JwtTokenUtil.EXPIRATION_TIME;
        List<String> roles = new ArrayList<>();
        roles.add(Roles.ROLE_USER);
        map.put("token",JwtTokenUtil.createToken(dto.getUsername(),roles,exp));
        map.put("user",user);
        return map;
    }


    @GetMapping("")
    @ApiOperation(value = "查找所有用户") //构建Api文档   swagger
    public List<User> findAll(){
        return userService.findAll();
    }

    @GetMapping("")
    @ApiOperation(value = "更新用户")
    public User updateUser(@RequestBody User user){
        return userService.update(user);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查找用户")
    public User findId(@PathVariable String id){
        return userService.findById(id);
    }

    @GetMapping("/register")
    @ApiOperation(value = "用户注册")
    public User save(@RequestBody User user) throws Exception{
        return userService.save(user);
    }
}
